package com.vercon.otamirror.service;

import static com.vercon.otamirror.MainApplication.policyManager;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.abupdate.iot_libs.OtaAgentPolicy;
import com.abupdate.iot_libs.data.remote.VersionInfo;
import com.abupdate.iot_libs.interact.callback.ICheckVersionCallback;
import com.vercon.commonmirror.Constants;
import com.vercon.commonmirror.cache.MirrorDataStorage;
import com.vercon.commonmirror.utils.APPUtil;
import com.vercon.commonmirror.utils.LogUtils;
import com.vercon.otamirror.MainActivity;
import com.vercon.otamirror.OtaActivity;
import com.vercon.otamirror.dialog.FirmwareUpdateDialog;
import com.vercon.otamirror.dialog.UpdateFirmwareDialog;
import com.vercon.otamirror.mode.FirmwareMode;
import com.vercon.otamirror.utils.helper.AppUtil;
import com.vercon.otamirror.utils.helper.FragmentOpenManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;


/**
 * Created by dongzhong on 2018/5/30.
 */

public class FloatService extends Service {
    public static boolean isStarted = false;

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        showFloatingWindow();
        getVersion();
        LogUtils.e("BootCompleteReceiver", "开机启动");
//        Observable.interval(1000, TimeUnit.MILLISECONDS)
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<Long>() {
//                    @Override
//                    public void accept(Long aLong) throws Exception {
//                        // EventBus.getDefault().post(new BlueToothAdd_NoEvent());
//                        LogUtils.e("BootCompleteReceiver", "ota在执行");
//
//                    }
//                });

        return super.onStartCommand(intent, flags, startId);
    }

    private void showFloatingWindow() {
//        view = LayoutInflater.from(this).inflate(R.layout.window_floating, null);
//        mIv_point = view.findViewById(R.id.iv_point);
//        mRl_content = view.findViewById(R.id.rl_content);
//        mIv_point.setVisibility(View.VISIBLE);
//        mRl_content.setVisibility(View.GONE);
//        mWindowManager.addView(view, layoutParams);
//        initListener();
    }

    private void initListener() {
//        view.setOnTouchListener(this);
//        mRl_content.setOnClickListener(this);
//        view.findViewById(R.id.tv_back).setOnClickListener(this);
//        view.findViewById(R.id.tv_home).setOnClickListener(this);
//        view.findViewById(R.id.tv_exit).setOnClickListener(this);

    }

//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.rl_content:
//                mIv_point.setVisibility(View.VISIBLE);
//                mRl_content.setVisibility(View.GONE);
//                layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
//                layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
//                mWindowManager.updateViewLayout(view, layoutParams);
//                break;
//            case R.id.tv_back:
//
//                break;
//            case R.id.tv_home:
//
//                break;
//            case R.id.tv_exit:
//
//                break;
//        }
//    }

    private void getVersion() {

        /**
         * 检测版本
         * 异步回调请求方法，可以在子线程中调用，也可在主线程中调用，回调方法在主线程，便于UI处理。
         */
        OtaAgentPolicy.checkVersion().enqueue(new ICheckVersionCallback() {
            @Override
            public void onCheckSuccess(List<VersionInfo> infoList) {
                //发现有新版本
                LogUtils.d("FotaApplication 发现有新版本 " + infoList.size());
                for (VersionInfo info : infoList) {
                    LogUtils.d("FotaApplication 版本 " + info.toString());
                }
                try {
                    VersionInfo  versionInfo =  infoList.get(0);
                    LogUtils.d("FotaApplication 发现有新版本 " + infoList.size());
                    if (policyManager != null) {
                        FirmwareMode mode = new FirmwareMode(APPUtil.getFirmwareUpdateVersion_k(versionInfo.versionName),
                                APPUtil.getFirmwareUpdateVersion_k(versionInfo.oldVersionName), versionInfo.deltaUrl,
                                AppUtil.getContent(versionInfo.content), true, versionInfo.publishDate, true);
                        LogUtils.i("FotaApplication", "33");
                        Intent intent = new Intent(getApplicationContext(), OtaActivity.class);
                        intent.putExtra(OtaActivity.otaData,mode);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }else {
                        LogUtils.i("FotaApplication", "policyManager为空");
                    }
                }catch (Exception e){
                    LogUtils.i("FotaApplication", "Exception="+e.getMessage());
                }


            }

            @Override
            public void onCheckFail(int errorCode) {
                //没有新版本

                LogUtils.d("FotaApplication 没有新版本 " + errorCode);

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void MessageEvent(FirmwareMode mode) {
        LogUtils.e(" FotaApplication ota推送的升级");
        Intent intent = new Intent(getApplicationContext(), OtaActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(OtaActivity.otaData,mode);
        startActivity(intent);


    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        isStarted = false;
        super.onDestroy();
    }
}
